package com.ciwong.epaper.modules.epaper.ui.listenspeak;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import com.ciwong.epaper.R;
import com.ciwong.epaper.modules.dbbean.LswAnswer;
import com.ciwong.epaper.modules.epaper.bean.ListenspeakExam;
import com.ciwong.epaper.modules.epaper.bean.Questions;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.epaper.dao.LswDao;
import com.ciwong.epaper.modules.epaper.util.EpaperJumpManager;
import com.ciwong.epaper.modules.epaper.util.ListenSpeakUtil;
import com.ciwong.epaper.modules.evaluate.ui.SentenceRepeatActivity;
import com.ciwong.epaper.ui.MainActivity;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.widget.NetWorkTipsDialog;
import com.ciwong.epaper.widget.NewLoginDialog;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.ui.BaseActivity;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 2016/12/13.
 */
public class ListenSpeakRetryActivity extends BaseActivity implements View.OnClickListener {

    public static final String TAG = "retryscore2";

    private Button btn_retry_evaluate_score;
    private TextView tx_fail_question_count;
    private View handle_evaluateing;
    private View handle_retry_page;
    private SeekBar seek_bar_make_score;

    private int mRetryIndex = 0;

    private RetryQuestionAdapter mRetryQuestionAdapter;
    private int progress = 0;
    private Timer timer = new Timer();
    private NetWorkTipsDialog mNetWorkTipsDialog;
    private ListView list_view;
    protected ArrayList<LswAnswer> mLswAnswerList = new ArrayList<LswAnswer>();
    private String mUuidSaveKey;
    private int workTime;

    private List<LswAnswer> lswAnswerList;


    //听说模考试卷
    protected ListenspeakExam mExamData;

    @Override
    protected int setView() {
        return R.layout.activity_listen_speak_retry;
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (null != mNetWorkTipsDialog && mNetWorkTipsDialog.isShowing()) {
                mNetWorkTipsDialog.dismiss();
            }

        }
    };

    @Override
    protected void findViews() {

        btn_retry_evaluate_score = (Button) findViewById(R.id.btn_retry_evaluate_score);
        tx_fail_question_count = (TextView) findViewById(R.id.tx_fail_question_count);
        seek_bar_make_score = (SeekBar) findViewById(R.id.seek_bar_make_score);
        handle_evaluateing = findViewById(R.id.handle_evaluateing);
        handle_retry_page = findViewById(R.id.handle_retry_page);
        list_view = (ListView) findViewById(R.id.list_view);

    }

    @Override
    protected void initEvent() {
        btn_retry_evaluate_score.setOnClickListener(this);
    }

    @Override
    protected void init() {
        setTitleText(R.string.str_score);

        workTime = getIntent().getIntExtra(IntentFlag.INTENT_FLAG_WORK_TIME, 0);
        mUuidSaveKey = getIntent().getStringExtra(IntentFlag.INTENT_FLAG_STR);
        mLswAnswerList = (ArrayList<LswAnswer>) getIntent().getSerializableExtra(IntentFlag.INTENT_FLAG_OBJ_LIST);

        if (mLswAnswerList != null) {
            tx_fail_question_count.setText(getFailLswAnswerList().size() + " " + getString(R.string.str_evaluate_fail));
        }

        if (null != mLswAnswerList && mLswAnswerList.size() > 0) {

//            for(int i=0;i<mLswAnswerList.size();i++) {
//                mLswAnswerList.get(i).setQuestionNumber(String.valueOf(i+1));
//            }

            mRetryQuestionAdapter = new RetryQuestionAdapter(ListenSpeakRetryActivity.this, getFailLswAnswerList());
            list_view.setAdapter(mRetryQuestionAdapter);
            String resPath = getIntent().getStringExtra(IntentFlag.INTENT_FLAG_EPAPER_RES_PATH);

            if (null != resPath) {
                initQuestionNumber(resPath);
            }

        }

    }

    @Override
    protected void loadData() {

    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (R.id.btn_retry_evaluate_score == id) {
            if(EConstants.IS_YOUKE){
                NewLoginDialog newLoginDialog=new NewLoginDialog(ListenSpeakRetryActivity.this);
                newLoginDialog.showLoginDialog();
            }else {
                if (true) {
                    if (mLswAnswerList != null && mLswAnswerList.size() > 0) {

                        mRetryIndex = 0;
                        for (int i = mRetryIndex; i <= mLswAnswerList.size(); i++) {
                            mRetryIndex = i;
                            if (i < mLswAnswerList.size() && mLswAnswerList.get(i).getUploadState() == LswAnswer.FAIL) {
                                break;
                            }
                        }

                        handle_retry_page.setVisibility(View.GONE);
                        handle_evaluateing.setVisibility(View.VISIBLE);
                        seek_bar_make_score.setProgress(0);
                        progress = 0;

                        timer.schedule(new TimerTask() {
                            @Override
                            public void run() {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {

                                    }
                                });

                                progress++;
                                seek_bar_make_score.setProgress(progress);
                                if (progress >= seek_bar_make_score.getMax()) {
                                    progress = 0;
                                }
//                            if (isLsOver)
                                {// 评分结束
                                    cancel();
                                }
                            }
                        }, 0, 1000);
                    }

                    onUploadStateDeal();


                } else {

                    mNetWorkTipsDialog = new NetWorkTipsDialog(this, getString(R.string.connect_disable3));
                    mNetWorkTipsDialog.show();
                    mHandler.sendEmptyMessageDelayed(0, 2000);

                }
            }


        }
    }


    private void onUploadStateDeal() {

        if (null != mLswAnswerList && mRetryIndex < mLswAnswerList.size()) {

            LswAnswer lswAnswer = mLswAnswerList.get(mRetryIndex);
            if(!EConstants.IS_YOUKE){
                LswDao.getInstance().submitMakeScore(lswAnswer,false, new BaseCallBack() {
                    @Override
                    public void success(Object data) {
                        mLswAnswerList.get(mRetryIndex).setUploadState(LswAnswer.SUCCESS);

                        Log.d(TAG, "##########重新上传成功#########");

                        retryCallback(true);
                    }

                    @Override
                    public void failed(int errorCode, Object data) {
                        failed(data);
                    }

                    @Override
                    public void failed(Object data) {
                        mLswAnswerList.get(mRetryIndex).setUploadState(LswAnswer.FAIL);
                        Log.d(TAG, "##########重新上传失败#########");

                        retryCallback(false);
                    }
                });
            }


        }
    }


    private void retryCallback(boolean isSuccess) {

        mRetryIndex++;
//          等于  列表遍历完都木有失败
        for (int i = mRetryIndex; i <= mLswAnswerList.size(); i++) {
            mRetryIndex = i;
            if (i < mLswAnswerList.size() && mLswAnswerList.get(i).getUploadState() == LswAnswer.FAIL) {
                break;
            }
        }

        if (mRetryIndex < mLswAnswerList.size()) {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
//                int progress = mRetryIndex * 100 / (mRetryQuestionList.size() + mRetrySuccessList.size());
                    seek_bar_make_score.setProgress(progress);
                }
            });
            //下一题未上传成功的
            onUploadStateDeal();

        } else {

            if (!isHashUploadFail()) {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //全部重试成功
                        tx_fail_question_count.setText(getFailLswAnswerList().size() + " " + getString(R.string.str_evaluate_fail));
                        handle_evaluateing.setVisibility(View.GONE);
                        handle_retry_page.setVisibility(View.VISIBLE);
                        mRetryQuestionAdapter.setRetryQuestionList(getFailLswAnswerList());
                        mRetryQuestionAdapter.notifyDataSetChanged();
                        jumpResult();
                    }
                });

            } else {
                //如果有未成功的，下一轮
                mRetryQuestionAdapter.notifyDataSetChanged();
                tx_fail_question_count.setText(getFailLswAnswerList().size() + " " + getString(R.string.str_evaluate_fail));
                handle_evaluateing.setVisibility(View.GONE);
                handle_retry_page.setVisibility(View.VISIBLE);

            }
        }
    }


    private void jumpResult() {

//        EpaperJumpManager.jumpToListenSpeakResult(R.string.listen_speak,
//                ListenSpeakRetryActivity.this,  mUuidSaveKey, workTime ,mLswAnswerList,
//                MainActivity.REQUEST_CODE_TO_DO_WORK);
//        setResult(RESULT_OK);
        finish();

    }

    /**
     * 是否还有文件上传失败
     *
     * @return
     */
    private boolean isHashUploadFail() {
        for (LswAnswer lswAnswer : mLswAnswerList) {
            if (lswAnswer.getUploadState() == LswAnswer.FAIL) {
                return true;
            }
        }
        return false;
    }

    private ArrayList<LswAnswer> getFailLswAnswerList() {

        ArrayList<LswAnswer> failList = new ArrayList<LswAnswer>();
        for (LswAnswer lswAnswer : mLswAnswerList) {
            if (lswAnswer.getUploadState() == LswAnswer.FAIL) {
                failList.add(lswAnswer);
            }
        }
        return failList;
    }


    private void initQuestionNumber(String path) {

        EpaperDao.getInstance().getSerializableObjects(path,
                ListenspeakExam.class, new BaseCallBack() {

                    @Override
                    public void success(final Object data) {
                        super.success(data);
                        mExamData = (ListenspeakExam) data;

                        List<Questions> mAllQuestionsList = ListenSpeakUtil.getSortQuestionList(mExamData.getItems());

                        if (mAllQuestionsList != null && mAllQuestionsList.size() > 0) {

                            CWLog.d(TAG, "##########mAllQuestionsList.size()#############" + mAllQuestionsList.size());
                            //把所有题目遍历出来，然后匹配失败的列表，位置是在所有题目的位置
                            for (int i = 0; i < mLswAnswerList.size(); i++) {
                                for (int j = 0; j < mAllQuestionsList.size(); j++) {
                                    if (mLswAnswerList.get(i).getVersionId().equals(mAllQuestionsList.get(j).getVersionId())) {
                                        if (null != mAllQuestionsList.get(j).getSort() && !mAllQuestionsList.get(j).getSort().equals("")) {
//                                            mLswAnswerList.get(i).setQuestionNumber(mAllQuestionsList.get(j).getSort());
                                        } else {
//                                            mLswAnswerList.get(i).setQuestionNumber(String.valueOf(j+1));
                                        }
                                        break;
                                    }
                                }

                            }
                        }

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mRetryQuestionAdapter.notifyDataSetChanged();
                            }
                        });
                    }

                    @Override
                    public void failed(int errorCode, Object data) {
                        failed(data);
                    }

                    @Override
                    public void failed(Object data) {
//                        finish();
//                        showToastError((int) data);

                        hideMiddleProgressBar();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mRetryQuestionAdapter.notifyDataSetChanged();
                            }
                        });
                    }
                }

        );
    }


}
